<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="128px">
      <el-form-item label="姓名" prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入姓名"
            clearable
            @keyup.enter="handleQuery"
            :disabled="isIdCardDisabled"
        />
      </el-form-item>
      <el-form-item label="身份证号" prop="idCard">
        <el-input
            v-model="queryParams.idCard"
            placeholder="请输入身份证号"
            clearable
            @keyup.enter="handleQuery"
            :disabled="isIdCardDisabled"
        />
      </el-form-item>
      <el-form-item label="电话" prop="phone">
        <el-input
            v-model="queryParams.phone"
            placeholder="请输入电话"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="预约日期" prop="reserveDate">
        <el-date-picker
            v-model="daterangeReserveDate"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleDateChange"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="单位名称" prop="unitName">
        <el-input
            v-model="queryParams.unitName"
            placeholder="请输入单位名称"
            clearable
            @keyup.enter="handleQuery"
            :disabled="isIdCardDisabled"
        />
      </el-form-item>
      <el-form-item label="机构代码" prop="socialCreditCode">
        <el-input
            v-model="queryParams.socialCreditCode"
            placeholder="请输入机构代码"
            clearable
            @keyup.enter="handleQuery"
            :disabled="isIdCardDisabled"
        />
      </el-form-item>
      <el-form-item label="体检状态" prop="tjStatus"
      >
        <el-select v-model="queryParams.tjStatus" placeholder="请选择" clearable style="width: 140px">
          <el-option label="已预约" :value="0"></el-option>
          <el-option label="体检中" :value="1"></el-option>
          <el-option label="已结束" :value="2"></el-option>
          <el-option label="已过期" :value="3"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="体检结果" prop="qualify">
        <el-select v-model="queryParams.qualify" placeholder="请选择" clearable style="width: 140px">
          <el-option label="合格" :value="1"></el-option>
          <el-option label="不合格" :value="2"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="发证状态" prop="isSendCard">
        <el-select v-model="queryParams.isSendCard" placeholder="请选择" clearable style="width: 140px">
          <el-option label="未发证" :value="0"></el-option>
          <el-option label="可发证" :value="1"></el-option>
          <el-option label="已发证" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="预约类型" prop="reserveType">
        <el-select v-model="queryParams.reserveType" placeholder="请选择" clearable style="width: 140px">
          <el-option label="自费预约" :value="1"></el-option>
          <el-option label="免费预约" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="体检机构" prop="reserveHospital">
        <el-select v-model="queryParams.reserveHospital" filterable placeholder="请选择体检机构" style="width: 180px">
          <el-option
              v-for="item in reserveHospitals"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>

    </el-form>
    <el-form-item>
      <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
      <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      <el-col :span="1.5" style="margin-left: 10px;margin-right: 10px">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['health:reserve:export']">
          导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="CreditCard" :disabled="multiple" @click="handleSendCard"
                   v-hasPermi="['system:user:sendCard']">批量发证
        </el-button>
      </el-col>
    </el-form-item>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['health:reserve:add']"
        >新增自费预约人员
        </el-button>
      </el-col>
      <!--            <el-col :span="1.5">-->
      <!--              <el-button-->
      <!--                type="success"-->
      <!--                plain-->
      <!--                icon="Edit"-->
      <!--                :disabled="single"-->
      <!--                @click="handleUpdate"-->
      <!--                v-hasPermi="['health:reserve:edit']"-->
      <!--              >修改</el-button>-->
      <!--            </el-col>-->
      <!--            <el-col :span="1.5">-->
      <!--              <el-button-->
      <!--                type="danger"-->
      <!--                plain-->
      <!--                icon="Delete"-->
      <!--                :disabled="multiple"-->
      <!--                @click="handleDelete"-->
      <!--                v-hasPermi="['health:reserve:remove']"-->
      <!--              >删除</el-button>-->
      <!--            </el-col>-->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="reserveList" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" align="center"/>
      <!--      <el-table-column label="主键" align="center" width="70" prop="id" hidden="hidden"/>-->
      <el-table-column label="姓名" align="center" width="70" prop="name" fixed="left"/>
      <el-table-column label="身份证号" align="center" prop="idCard" width="180" show-overflow-tooltip="true"/>
      <el-table-column label="电话" align="center" prop="phone" width="130"/>
      <el-table-column label="预约医院" align="center" prop="reserveHospital" show-overflow-tooltip="true" width="150">
        <template #default="scope">
          <span>{{ getJobTypeLabel(scope.row.reserveHospital, hospitals) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="预约日期" align="center" prop="reserveDate" width="100">
        <template #default="scope">
          <span>{{ parseTime(scope.row.reserveDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预约时间" align="center" prop="reserveHour" width="100"/>
      <el-table-column label="是否单位" align="center" prop="isUnit" width="90">
        <template #default="scope">
          {{ scope.row.isUnit === 1 ? '是' : scope.row.isUnit === 0 ? '否' : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="单位名称" align="center" prop="unitName" width="180" show-overflow-tooltip="true"/>
      <el-table-column label="机构代码" align="center" prop="socialCreditCode" width="200"/>
      <el-table-column label="体检状态" align="center" prop="tjStatus" width="100">
        <template #default="scope">
          <el-tag :type="getTjStatusTagType(scope.row.tjStatus)">
            {{ getTjStatusLabel(scope.row.tjStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态修改日期" align="center" prop="qualifyDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.qualifyDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="体检结果" align="center" prop="qualify" width="100">
        <template #default="scope">
          <el-tag :type="getQualifyTagType(scope.row.qualify)">
            {{ getQualifyLabel(scope.row.qualify) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="结果文件" align="center" width="130">
        <template #default="scope">
          <!--preview-teleported:解决elementPlus中表格中图片放大层级问题-->
          <el-image
              preview-teleported
              v-if="scope.row.tjResult"
              :src="baseUrl+scope.row.tjResult"
              :preview-src-list="[baseUrl+scope.row.tjResult]"
              :initial-index="0"
              fit="cover"
              style="width: 80px; height: 60px; cursor: pointer;"
          />
          <span v-else>—</span>
        </template>
      </el-table-column>
      <el-table-column label="头像文件" align="center" width="130">
        <template #default="scope">
          <!--preview-teleported:解决elementPlus中表格中图片放大层级问题-->
          <el-image
              preview-teleported
              v-if="scope.row.employeeAvatar"
              :src="baseUrl+scope.row.employeeAvatar"
              :preview-src-list="[baseUrl+scope.row.employeeAvatar]"
              :initial-index="0"
              fit="cover"
              style="width: 80px; height: 60px; cursor: pointer;"
          />
          <span v-else>—</span>
        </template>
      </el-table-column>

      <el-table-column label="发证状态" align="center" prop="isSendCard" fixed="right" width="90">
        <template #default="scope">
          <el-tag :type="getIsSendCardTagType(scope.row.isSendCard)">
            {{ getIsSendCardLabel(scope.row.isSendCard) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="下载证件" align="center" prop="download" fixed="right" width="90">
        <template #default="scope">
          <el-button v-if="scope.row.isSendCard === 1" link type="success" icon="Download"
                     @click="downloadCard(scope.row)"
                     v-hasPermi="['health:reserve:downloadCard']">下载
          </el-button>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="200"
                       v-hasPermi="['health:reserve:edit']">
        <template #default="scope">
          <el-button link type="warning" icon="MessageBox" @click="handleSendCard(scope.row)"
                     v-hasPermi="['health:reserve:sendCard']">发证
          </el-button>
          <el-button link type="primary" icon="MessageBox" @click="handleUpload(scope.row)"
                     v-hasPermi="['health:reserve:upload']">上传文件
          </el-button>
          <br/>
          <el-button link type="success" icon="EditPen" @click="handleEdit(scope.row)"
                     v-hasPermi="['health:reserve:edit']">修改
          </el-button>
          <el-button link type="primary" icon="EditPen" @click="handleUpdate(scope.row)"
                     v-hasPermi="['health:reserve:edit']">修改状态
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 修改从业人员预约信息对话框 -->
    <el-dialog title="修改从业人员预约信息" v-model="openEdit" width="650px" append-to-body>
      <el-form ref="reserveEditRef" :model="editForm" :rules="addRules" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入姓名"/>
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="editForm.idCard" placeholder="请输入身份证号"/>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入电话"/>
        </el-form-item>
        <el-form-item label="预约医院" prop="reserveHospital">
          <el-select v-model="editForm.reserveHospital" filterable
                     placeholder="请选择预约医院">
            <el-option
                v-for="item in reserveHospitals"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="预约日期" prop="reserveDate">
          <el-date-picker clearable
                          v-model="editForm.reserveDate"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择预约日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="预约时间" prop="reserveHour">
          <el-input v-model="editForm.reserveHour"/>
        </el-form-item>
        <el-form-item label="预约类型" prop="reserveType">
          <el-select v-model="editForm.reserveType" placeholder="请选择预约类型">
            <el-option label="自费预约" :value=1></el-option>
            <el-option label="免费预约" :value=2></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否单位" prop="isUnit">
          <el-select v-model="editForm.isUnit" placeholder="请选择是否为单位">
            <el-option label="是" :value=1></el-option>
            <el-option label="否" :value=0></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单位名称" prop="unitName">
          <el-input v-model="editForm.unitName" placeholder="请输入单位名称"/>
        </el-form-item>
        <el-form-item label="组织机构代码" prop="socialCreditCode">
          <el-input v-model="editForm.socialCreditCode" placeholder="请输入组织机构代码"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitEditForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 修改从业人员状态预约对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="reserveRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="体检状态" prop="tjStatus">
          <el-select v-model="form.tjStatus" placeholder="请选择">
            <el-option label="已预约" :value=0></el-option>
            <el-option label="体检中" :value=1></el-option>
            <el-option label="已结束" :value=2></el-option>
            <el-option label="已过期" :value=3></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="体检结果" prop="qualify">
          <el-select v-model="form.qualify" placeholder="请选择">
            <el-option label="-" :value=0></el-option>
            <el-option label="合格" :value=1></el-option>
            <el-option label="不合格" :value=2></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发证状态" prop="qualify">
          <el-select v-model="form.isSendCard" placeholder="请选择">
            <el-option label="未发证" :value=0></el-option>
            <el-option disabled label="可发证" :value=1></el-option>
            <el-option label="已发证" :value=2 v-hasPermi="['system:user:sendCard']"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加自费从业人员状态预约对话框 -->
    <el-dialog title="添加自费预约人员" v-model="openAdd" width="600px" append-to-body>
      <el-form ref="reserveAddRef" :model="addForm" :rules="addRules" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入姓名"/>
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="addForm.idCard" placeholder="请输入身份证号"/>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="addForm.phone" placeholder="请输入电话"/>
        </el-form-item>
        <el-form-item label="家庭地址" prop="address">
          <el-input v-model="addForm.address" placeholder="请输入地址"/>
        </el-form-item>
        <el-form-item label="预约医院" prop="reserveHospital">
          <el-select v-model="addForm.reserveHospital" filterable
                     placeholder="请选择预约医院">
            <el-option
                v-for="item in reserveHospitals"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="民族" prop="ethnic">
          <el-select v-model="addForm.ethnic" filterable placeholder="请选择">
            <el-option
                v-for="item in ethnics"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工种" prop="jobTypeId">
          <!--              <el-select v-model="form.jobTypeId" filterable placeholder="请选择">-->
          <!--                <el-option-->
          <!--                    v-for="item in jobTypes"-->
          <!--                    :key="item.value"-->
          <!--                    :label="item.label"-->
          <!--                    :value="item.value"-->
          <!--                />-->
          <!--              </el-select>-->

          <!-- 当后端传来的数据量很大的时候,下拉框如果选择上面那种会加载很久,影响使用体验,可以换以下这种 el-select-v2标签 -->
          <el-select-v2
              v-model="addForm.jobTypeId"
              :options="jobTypes"
              filterable
              placeholder="请选择工种"
          />
        </el-form-item>
        <el-form-item label="预约日期" prop="reserveDate">
          <el-date-picker clearable
                          v-model="addForm.reserveDate"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择预约日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="预约时间" prop="reserveHour">
          <el-input v-model="addForm.reserveHour"/>
        </el-form-item>
        <el-form-item label="预约类型" prop="isUnit">
          <el-select v-model="addForm.reserveType" placeholder="请选择预约类型">
            <el-option label="自费预约" :value=1></el-option>
            <el-option label="免费预约" :value=2></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否单位" prop="isUnit">
          <el-select v-model="addForm.isUnit" placeholder="请选择是否为单位">
            <el-option label="是" :value=1></el-option>
            <el-option label="否" :value=0></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单位名称" prop="unitName">
          <el-input v-model="addForm.unitName" placeholder="请输入单位名称"/>
        </el-form-item>
        <el-form-item label="组织机构代码" prop="socialCreditCode">
          <el-input v-model="addForm.socialCreditCode" placeholder="请输入组织机构代码"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitAddForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!--  上传文件模态框  -->
    <el-dialog title="上传文件" v-model="openUpload" width="500px" append-to-body>
      <el-form ref="reserveRef" :model="form" :rules="rules" label-position="top">
        <!--   上传图片   -->
        <el-form-item label="上传体检结果文件:" prop="tjResult">
          <image-upload v-model="form.tjResult"/>
        </el-form-item>
        <!--   上传头像   -->
        <el-form-item label="上传头像文件:" prop="employeeAvatar">
          <image-upload v-model="form.employeeAvatar"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="Reserve">
import {
  addReserve,
  addSelfCostReserve,
  delReserve,
  downloadSendCard,
  getReserve,
  listReserve,
  updateIsSendCard,
  updateReserve,
} from "@/api/health/reserve"
import {
  ethnics,
  hospitals,
  jobTypes,
  loadAllHospitals,
  loadEthnic,
  loadJobTypes,
  loadReserveHospital,
  reserveHospitals
} from "@/api/employee/applyBaseData.js";
import {parseTime} from "@/utils/zillion.js";
import {ElMessage} from "element-plus";
import {debounce} from 'lodash-es'
import useUserStore from "@/store/modules/user.js";

const userStore = useUserStore()
const {proxy} = getCurrentInstance()
const daterangeReserveDate = ref([]) // 新增日期范围变量

// const baseUrl = "http://117.157.64.139:9100"
const baseUrl = import.meta.env.VITE_STATIC_BASE_URL
const reserveList = ref([])
const open = ref(false) // 修改状态模态框
const openEdit = ref(false) // 修改信息模态框
const openUpload = ref(false) // 上传文件模态框
const openAdd = ref(false) // 新增模态框
const loading = ref(true) // 加载动画
const showSearch = ref(true) // 展开搜索条件
const ids = ref([])
const names = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const daterangeCreateTime = ref([])
const isIdCardDisabled = ref(false); // 身份证输入框是否禁用 设置为 true 表示不可输入

// 自费预约人员添加表单
const addForm = ref({
  name: "",
  idCard: "",
  phone: "",
  reserveHospital: "",
  reserveDate: "",
  reserveHour: "8:30-10:30",
  isUnit: null,
  unitName: "",
  socialCreditCode: "",
  reserveType: 1, // 预约类型:自费
  ethnic: "",
  jobTypeId: null,
  address: "",
})

const editForm = ref({
  name: "",
  idCard: "",
  phone: "",
  reserveHospital: "",
  reserveDate: "",
  reserveHour: "8:30-10:30",
  isUnit: null,
  unitName: "",
  socialCreditCode: "",
  reserveType: null, // 预约类型:自费/免费
  ethnic: null,
  jobTypeId: null,
  address: "",
})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    idCard: null,
    phone: null,
    reserveHospital: null,
    reserveDate: null,
    reserveHour: null,
    isUnit: null,
    unitName: null,
    socialCreditCode: null,
    qualify: null,
    qualifyDate: null,
    tjStatus: null,
    tjResult: null,
    isSendCard: null,
    reserveType: null,
  },
  rules: {
    name: [
      {required: true, message: "姓名不能为空", trigger: "blur"}
    ],
    idCard: [
      {required: true, message: '请输入身份证号', trigger: 'blur'},
      {pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '身份证号格式不正确'}
    ],
    phone: [
      {required: true, message: '请输入联系电话', trigger: 'blur'},
      {pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确'}
    ],
    reserveHospital: [
      {required: true, message: "预约医院不能为空", trigger: "change"}
    ],
    reserveDate: [
      {required: true, message: "预约日期不能为空", trigger: "blur"}
    ],
    reserveHour: [
      {required: true, message: "预约时间不能为空", trigger: "change"}
    ],
  },
  addRules: {
    name: [
      {required: true, message: "姓名不能为空", trigger: "blur"}
    ],
    idCard: [
      {required: true, message: '请输入身份证号', trigger: 'blur'},
      {pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '身份证号格式不正确'}
    ],
    phone: [
      {required: true, message: '请输入联系电话', trigger: 'blur'},
      {pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确'}
    ],
    reserveHospital: [
      {required: true, message: "预约医院不能为空", trigger: "change"}
    ],
    reserveDate: [
      {required: true, message: "预约日期不能为空", trigger: "blur"}
    ],
    reserveHour: [
      {required: true, message: "预约时间不能为空", trigger: "change"}
    ],
    isUnit: [
      {required: true, message: "是否单位不能为空", trigger: "change"}
    ],
    jobTypeId: [
      {required: true, message: '请选择工种', trigger: 'change'}
    ],
    ethnic: [
      {required: true, message: '请选择民族', trigger: 'change'}
    ],
    address: [
      {required: true, message: '请输入家庭地址', trigger: 'blur'}
    ],
  }
})

const {queryParams, form, rules, addRules} = toRefs(data)

// 获取体检列表状态
function getTjStatusLabel(status) {
  switch (status) {
    case 0:
      return '已预约';
    case 1:
      return '体检中';
    case 2:
      return '已结束';
    case 3:
      return '已过期';
    default:
      return '-';
  }
}

// 获取体检状态标签类型
function getTjStatusTagType(status) {
  switch (status) {
    case 0: // 已预约
      return 'primary';
    case 1: // 体检中
      return 'warning';
    case 2: // 已结束
      return 'success';
    case 3: // 已过期
      return 'danger';
    default:
      return 'info';
  }
}


// 获取体检结果标签样式
function getQualifyTagType(qualify) {
  if (qualify === 1) return 'success';
  if (qualify === 2) return 'danger';
  return 'info';
}

// 获取发证状态标签样式
function getIsSendCardTagType(isSendCard) {
  if (isSendCard === 2) return 'success';
  if (isSendCard === 1) return 'warning';
  if (isSendCard === 0) return 'danger';
  return 'info';
}

// 获取体检结果标签
function getQualifyLabel(qualify) {
  if (qualify === 0) return '-';
  if (qualify === 1) return '合格';
  if (qualify === 2) return '不合格';
  return '-';
}

// 获取体检结果标签
function getIsSendCardLabel(isSendCard) {
  if (isSendCard === 0) return '未发证';
  if (isSendCard === 1) return '可发证';
  if (isSendCard === 2) return '已发证';
  return '-';
}

// 日期范围变化
function handleDateChange(dates) {
  if (dates && dates.length === 2) {
    queryParams.value.reserveBeginDate = dates[0]
    queryParams.value.reserveEndDate = dates[1]
  } else {
    queryParams.value.reserveBeginDate = null
    queryParams.value.reserveEndDate = null
  }
}

/** 查询从业人员预约列表 */
function getList() {
  loading.value = true
  queryParams.value.params = {}
  if (null != daterangeCreateTime && '' != daterangeCreateTime) {
    queryParams.value.params["beginCreateTime"] = daterangeCreateTime.value[0]
    queryParams.value.params["endCreateTime"] = daterangeCreateTime.value[1]
  }
  // 判断登录用户是系统用户还是普通用户 normal
  userStore.getInfo().then((res) => {
    // 获取登录用户类型
    const userType = res.user.userType;
    // 获取唯一识别码
    const idCard = res.user.identifyCode;
    // 获取姓名
    const nickName = res.user.nickName;

    // 获取角色
    const roles = res.roles;
    const role = roles[0];

    // 如果用户为普通用户,那么就查询当前用户的数据
    if ('normal' === role) {
      if ("01" === userType) {
        queryParams.value.name = nickName;
        queryParams.value.idCard = idCard;
        isIdCardDisabled.value = true;
      } else if ("02" === userType) {
        queryParams.value.unitName = nickName;
        queryParams.value.idCard = idCard;
        isIdCardDisabled.value = true;
      }
      getData()
    } else {
      getData()
    }
  });
}

function getData() {
  listReserve(queryParams.value).then(response => {
    // console.log('查询列表返回结果:', response)
    reserveList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  openEdit.value = false
  openUpload.value = false
  openAdd.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    idCard: null,
    phone: null,
    reserveHospital: null,
    reserveDate: null,
    reserveHour: null,
    isUnit: null,
    unitName: null,
    socialCreditCode: null,
    qualify: null,
    qualifyDate: null,
    tjStatus: null,
    tjResult: null,
    createTime: null,
    employeeAvatar: null,
    isSendCard: null,
  }
  addForm.value = {
    id: null,
    name: '',
    idCard: '',
    phone: '',
    reserveHospital: '',
    reserveDate: '',
    reserveHour: '8:30-10:30',
    isUnit: null,
    unitName: '',
    socialCreditCode: '',
    ethnic: "",
    jobTypeId: null,
    address: "",
  }
  editForm.value = {
    id: null,
    name: '',
    idCard: '',
    phone: '',
    reserveHospital: '',
    reserveDate: '',
    reserveHour: '8:30-10:30',
    isUnit: null,
    unitName: '',
    socialCreditCode: '',
    ethnic: "",
    jobTypeId: null,
    address: "",
  }
  proxy.resetForm("reserveRef")
  proxy.resetForm("reserveAddRef")
  proxy.resetForm("reserveEditRef")

}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeCreateTime.value = []
  daterangeReserveDate.value = [] // 重置预约日期范围
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  names.value = selection.map(item => item.name)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  openAdd.value = true
  loadReserveHospital(100)
  loadEthnic()
  loadJobTypes()
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getReserve(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改体检状态/结果"
  })
}

// 防抖submitForm（600ms 内重复点击不会触发）
const submitForm = debounce(rawSubmitForm, 600)

/** 提交数据 */
function rawSubmitForm() {
  proxy.$refs["reserveRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        console.log("修改数据:", form.value);
        updateReserve(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          openUpload.value = false
          getList()
        })
      } else {
        addReserve(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          openUpload.value = false
          getList()
        })
      }
    }
  })
}

// 上传文件按钮操作
function handleUpload(row) {
  reset()
  const _id = row.id || ids.value
  getReserve(_id).then(response => {
    form.value = response.data
    openUpload.value = true
  })
}

/** 处理发证状态 */
function handleSendCard(row) {
  const _ids = row.id || ids.value
  const _names = row.name || names.value
  proxy.$modal.confirm('是否给 "' + _names + '" 的从业人员发证?').then(function () {
    return updateIsSendCard(_ids).then(response => {
      console.log(response)
      if (response.data.status === "SUCCESS") {
        proxy.$modal.msgSuccess("发证成功!");
      } else if (response.data.status === "FAILED") {
        var msg = response.data.msg;
        proxy.$modal.msgError("发证失败，" + msg);
      }
    })
  }).then(() => {
    getList()
  }).catch(() => {
  })
}


// 提交自费的预约人员相关信息
function submitAddForm() {
  proxy.$refs["reserveAddRef"].validate(valid => {
    if (valid) {
      // 如果为个人
      if (0 === addForm.value.isUnit) {
        addSelfCostReserve(addForm.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          openAdd.value = false
          getList()
        })
        // 如果为单位
      } else if (1 === addForm.value.isUnit) {
        if (addForm.value.unitName != "" && addForm.value.socialCreditCode != "") {
          addSelfCostReserve(addForm.value).then(response => {
            proxy.$modal.msgSuccess("新增成功")
            openAdd.value = false
            getList()
          })
        } else {
          proxy.$modal.msgError("请填写单位信息");
        }
      }

    }
  })
}

function handleEdit(row) {
  reset()
  const _id = row.id || ids.value
  getReserve(_id).then(response => {
    editForm.value = response.data
    openEdit.value = true
    title.value = "修改预约人员信息"
  })
}

function submitEditForm() {
  updateReserve(editForm.value).then(response => {
    proxy.$modal.msgSuccess("修改成功")
    openEdit.value = false
    getList()
  })
}

/**
 *
 * 下载健康证文件
 * @param row 下载的当前行数据
 */
function downloadCard(row) {
  downloadSendCard(row.id).then(response => {
    console.log(response)
    // 从返回信息中获取文件路径
    const filePath = response.msg

    // 拼接完整 URL（注意 baseUrl 要配置为后端域名或基础路径）
    // const baseUrl = 'http://117.157.64.139:9100/profile'
    const baseUrl = import.meta.env.VITE_STATIC_BASE_URL + "/profile"
    const fullUrl = baseUrl + filePath

    // 创建 <a> 标签并模拟点击进行下载
    const link = document.createElement('a')
    link.href = fullUrl
    link.setAttribute('download', '')
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)

    // 提示用户下载成功
    ElMessage.success('文件开始下载')
  }).catch(error => {
    console.error('下载失败:', error)
    ElMessage.error('文件下载失败')
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除从业人员预约编号为"' + _ids + '"的数据项？').then(function () {
    return delReserve(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('health/reserve/export', {
    ...queryParams.value
  }, `reserve_${new Date().getTime()}.xlsx`)
}

// 后台id转为中文展示方法
function getJobTypeLabel(id, list) {
  let lableName = list.find(item => item.value == id);
  return lableName ? lableName.label : '未知';
}

onMounted(() => {
  getList()
  loadAllHospitals()
  loadReserveHospital(100)
})
</script>
